package com.xxkj.orcfx.utils;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件读取工具类
 */
public class FileUtil {

    /**
     * 读取文件内容，作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }

        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        }

        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流  
        FileInputStream fis = new FileInputStream(filePath);
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];
        // 用于保存实际读取的字节数  
        int hasRead = 0;
        while ((hasRead = fis.read(bbuf)) > 0) {
            sb.append(new String(bbuf, 0, hasRead));
        }
        fis.close();
        return sb.toString();
    }

    public static String readFileAsString(File file) throws IOException {
        if (!file.exists()) {
            throw new FileNotFoundException(file.getPath());
        }

        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        }

        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流
        FileInputStream fis = new FileInputStream(file);
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];
        // 用于保存实际读取的字节数
        int hasRead = 0;
        while ((hasRead = fis.read(bbuf)) > 0) {
            sb.append(new String(bbuf, 0, hasRead));
        }
        fis.close();
        return sb.toString();
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(File file) throws IOException {
        if (!file.exists()) {
            throw new FileNotFoundException(file.getPath());
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;

            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];
                int len1;
                while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }

                byte[] var7 = bos.toByteArray();
                return var7;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;

            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];
                int len1;
                while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }

                byte[] var7 = bos.toByteArray();
                return var7;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }
    }


    public static String imageToBase64(BufferedImage bufferedImage) {
        Base64 encoder = new Base64();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "jpg", baos);
        } catch (IOException e) {
        }
        return new String(encoder.encode((baos.toByteArray())));

    }

    public static String decryptByBase64(String base64, String filePath) throws Exception {
        if (base64 == null && filePath == null) {
            throw new Exception("生成文件失败，无文件路径或者base64。");
        }
        try {
            Files.write(Paths.get(filePath), Base64.decode(base64), StandardOpenOption.CREATE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }


    /**
     * 压缩base64编码至4M以内
     *
     * @param base64Img
     * @return
     */
    public static String resizeImageTo4M(String base64Img) {
        try {
            org.apache.commons.codec.binary.Base64 decoder = new org.apache.commons.codec.binary.Base64();
            byte[] imageByte = decoder.decode(base64Img);
            InputStream stream = new ByteArrayInputStream(imageByte);
            BufferedImage src = ImageIO.read(stream);
            BufferedImage output = Thumbnails.of(src).size(2000, 2000).asBufferedImage();
            String base64 = imageToBase64(output);
            if (base64.length() - base64.length() / 8 * 2 > 4000000) {
                output = Thumbnails.of(output).scale(1 / (base64.length() / 4000000)).asBufferedImage();
                base64 = imageToBase64(output);
            }
            return base64;
        } catch (Exception e) {
            return base64Img;
        }
    }


    /**
     * 按行读取文件
     * @param filePath
     * @return
     * @throws IOException
     */
    public static List<String> readFile(String filePath) throws IOException {
        List<String> dateLineString = new ArrayList<>();
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            File file = new File(filePath);
            if(!file.exists()) {
                return dateLineString;
            }

            fis = new FileInputStream(filePath);
            isr = new InputStreamReader(fis, "UTF-8");
            br = new BufferedReader(isr);
            String line="";
            while ((line=br.readLine())!=null) {
                dateLineString.add(line);
            }
            br.close();
            isr.close();
            fis.close();
        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (Exception e){}
            }
            if(isr != null) {
                try {
                    isr.close();
                } catch (Exception e){}
            }
            if(fis != null) {
                try {
                    fis.close();
                } catch (Exception e){}
            }
        }
        return dateLineString;
    }

    /**
     * 按行写文件 - 追加文件
     * @param dataList
     * @throws IOException
     */
    public static void writeFile(String filePath, List<String> dataList) throws IOException {
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        BufferedWriter  bw = null;
        try {
            fos = new FileOutputStream(filePath);
            osw = new OutputStreamWriter(fos, "UTF-8");
//            osw = new FileWriter(filePath, append);
            bw = new BufferedWriter(osw);
            for(String arr : dataList){
                bw.write(arr);
                bw.newLine();
            }
        } finally {
            if(bw != null) {
                try {
                    bw.close();
                } catch (Exception e){}
            }
            if(osw != null) {
                try {
                    osw.close();
                } catch (Exception e){}
            }
            if(fos != null) {
                try {
                    fos.close();
                } catch (Exception e){}
            }
        }
    }
}
